#!/usr/bin/env python

# Uses the patched 'pygooglevoice' library. This will not work with the
# unpatched version. Go here to see the patch and a short discussion
# about it:
#
#   http://code.google.com/p/pygooglevoice/issues/detail?id=22#c12
#
# This also needs the BeautifulSoup XML parsing package. I tested this
# with the following version of that library:
#
#   http://www.crummy.com/software/BeautifulSoup/download/3.x/BeautifulSoup-3.0.8.1.tar.gz

from googlevoice import Voice
import re
import sys
import BeautifulSoup

def nextConversation(json, html) :
    tree = BeautifulSoup.BeautifulSoup(html)
    convBlock = tree.findAll('div', attrs={'id' : True}, recursive=False)
    jsonMessages = json['messages']
    for conv in convBlock :
        yield jsonMessages[conv['id']]
    return

voice = Voice()
voice.login()

conversations = []
page = 0
while True:
    page += 1
    voice.voicemail(page)
    
    count = 0
    for conv in nextConversation(voice.voicemail.data, voice.voicemail.html):
        count += 1
        conversations.insert(0, conv)
    print 'count %d' % count
    if count < 1:
        break
    print 'page %d' % page


## As a proof of concept, just print out the data structures for the
## earliest and latest conversation. You can iterate over the
## 'conversations' list to get the data for all of the conversations.

print len(conversations)
print '\n%s\n\n%s' % (repr(conversations[0]), repr(conversations[-1]))

import json
print json.dumps(conversations[0],sort_keys=True, indent=4)
